<?php
namespace Inationsoft\Koma;

use Inationsoft\NS;
use Inationsoft\NS\Core\Controller;

define('_NAMESPACE_', '\Inationsoft\Koma');

class Auth extends Controller {	
	function index() {
		if(User::getInstance()->isUser()) $this->redirect(NS\Config::getInstance()->Koma->LoginRedirect);

		NS\StyleManager::getInstance()->addSource($this->Path . '/assets/css/auth.css');

		$this->View->File = 'auth/form.php';
		$this->View->assign(array(
			'form_title' => NS\Config::getInstance()->Koma->Title,
			'username_caption' => 'Username' . new NS\WidgetHidden('username-placeholder', ('Username')),
			'username' => new NS\WidgetText('username', NS\Cookie::getInstance()->get('username'), 'Username', array(new NS\RequiredValidator(''), new NS\MinLengthValidator(3, ''), new NS\CompareValidator('username-placeholder', NS_VR_COMPARE_NOT_EQUALS, '')), array('class' => 'login-input')),
			'password_caption' => 'Password',
			'password' => new NS\WidgetPassword('password', null, 'Password', array(new NS\RequiredValidator(''), new NS\MinLengthValidator(3, '')), array('class' => 'login-input')),
			'remember' => new NS\WidgetCheckBox('remember', NS\Cookie::getInstance()->get('remember'), NS\Cookie::getInstance()->get('remember'), 'Remember Me'),
			'redirect' => new NS\WidgetHidden('redirect', NS_BASE_URL),
			'submit' => new NS\WidgetButton('submit', 'Login', NS_WID_BUTTON_SUBMIT)
		));

		NS\ValidatorManager::getInstance()->addValidate('login');
	}
	
	function login() {
		$m = NS\Model::getInstance('System', 'system');

		if($user_data = $m->getUser($this->Request->Post->value('username'), $this->Request->Post->value('password'))) {
			$_SESSION['Koma']['Token'] = $user_data['token'];

			if(!$user_data['status']) $this->redirect(NS\Config::getInstance()->Koma->LoginRedirect,  sprintf('Account is not yet activated, please activate the account first'));
			
			$user = new User();
			$user->UID = $user_data['uid'];
			$user->RID = $user_data['rid'];
			$user->Username = $user_data['username'];
			$user->Role = $user_data['role'];
			$user->FullName = $user_data['fullname'];
			$user->Token = md5($user_data['token'] . NS\Config::getInstance()->Application->Salt);
			$user->lock();

			$_SESSION['Koma']['User'] = serialize($user);
			session_regenerate_id();

			$this->redirect(NS\Config::getInstance()->Koma->LoginRedirect,  sprintf('Thank you for logging in, %s', $user_data['fullname']));
		}

		$this->redirect('system/auth', 'You have have incorrect username or password!');
	}

	function logout($token = '') {
		$user = User::getInstance();
		if($token == $user->Token && $token == md5($_SESSION['Koma']['Token'] . NS\Config::getInstance()->Application->Salt)) {
			$_SESSION['Koma'] = array();
			session_regenerate_id();
			
		}
		
		$this->redirect(NS\Config::getInstance()->Koma->LogoutRedirect);
	}
}
?>